package cn.zf233.xcloud.config.lockpool.impl;

import cn.zf233.xcloud.config.lockpool.IXCloudThreadPool;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by zf233 on 2021/6/1
 * XCloud单机部署的线程池
 */
public class SingleXCloudThreadPool implements IXCloudThreadPool<ReentrantLock> {

    private static final Map<Long, ReentrantLock> DOWNLOAD_LOCK_MAP = new ConcurrentHashMap<>();
    private static final Map<Long, ReentrantLock> CAPACITY_LOCK_MAP = new ConcurrentHashMap<>();

    @Override
    public ReentrantLock getDownloadLock(Long userId) { // 获取用户对应的下载文件锁
        return DOWNLOAD_LOCK_MAP.computeIfAbsent(userId, (id) -> new ReentrantLock());
    }

    @Override
    public ReentrantLock getCapacityLock(Long userId) { // 获取用户对应的容量操作锁（删除文件、上传文件等涉及到用户容量的操作）
        return CAPACITY_LOCK_MAP.computeIfAbsent(userId, (id) -> new ReentrantLock());
    }

    @Override
    public ReentrantLock getMoveOrCopyLock(Long userId) { // 获取用户对应的复制、移动操作锁（删除文件、复制文件、上传文件等涉及到用户容量的操作）
        return this.getCapacityLock(userId);
    }

    @Override
    public ReentrantLock getFileRenameLock(Long userId) { // 获取用户对应的重命名文件锁
        return this.getCapacityLock(userId);
    }

    @Override
    public ReentrantLock getShareLock(Long userId) { // 获取用户对应的共享文件锁
        return this.getCapacityLock(userId);
    }

    @Override
    public void unLock(ReentrantLock lock) {
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }

    @Override
    public void reset() { // 重置锁池
        DOWNLOAD_LOCK_MAP.clear();
        CAPACITY_LOCK_MAP.clear();
    }
}
